package com.mark.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mark.common.ServerResponse;
import com.mark.dao.CategoryMapper;
import com.mark.dao.ProductMapper;
import com.mark.dao.UserMapper;
import com.mark.enums.ProductStatusEnum;
import com.mark.exception.ProductException;
import com.mark.pojo.Category;
import com.mark.pojo.Product;
import com.mark.pojo.User;
import com.mark.service.ICategoryService;
import com.mark.service.IProductService;
import com.mark.vo.ProductDetailVo;
import com.mark.vo.ProductListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by Mark on 2018/3/26.
 * 商品模块service层业务具体实现类
 */
@Service("productServiceImpl")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ICategoryService iCategoryService;
    @Autowired
    private UserMapper userMapper;

    /**
     *后台
     */
    //1.增加产品的业务逻辑：根据ID是否为空执行保存或者更新操作
    @Override
    public ServerResponse insertOrUpdateProduct(Product product) {
        try {
            //从前端接受过来的 详细图片地址subImgsAddr字段为以逗号分隔的字符串。选取一个字符串另存为主图地址
            if (StringUtils.isNotBlank(product.getSubImgsAddr())) {
                String[] subImageArray = product.getSubImgsAddr().split(",");
                if (subImageArray.length > 0) {
                    product.setMainImgAddr(subImageArray[0]);
                }
            }
            //判断是更新还是插入操作
            if (product.getId() != null) {//更新
                product.setEnableStatus(1);
                int rowCount = productMapper.updateByPrimaryKeySelective(product);
                if (rowCount >= 0) {
                    return ServerResponse.createBySuccessMessage("更新产品成功");
                }
                return ServerResponse.createByErrorMessage("更新产品失败");
            } else {//新增
                product.setEnableStatus(1);
                product.setPriority(1);
                int rowCount = productMapper.insert(product);
                if (rowCount >= 0) {
                    return ServerResponse.createBySuccessMessage("新增产品成功");
                }
                return ServerResponse.createByErrorMessage("新增产品失败");
            }
        }catch (Exception e){
            throw new ProductException("insertOrUpdateProduct",e.getClass()+e.getMessage());
        }
    }

    //2.修改商品销售状态的业务逻辑
    @Override
    public ServerResponse setSaleStatus(Integer productId,Integer status) {
        try {
            Product product = new Product();
            product.setId(productId);
            product.setEnableStatus(status);
            int rowCount = productMapper.updateByPrimaryKeySelective(product);
            if(rowCount > 0){
                return  ServerResponse.createBySuccess("修改商品状态成功");
            }
            return ServerResponse.createByErrorMessage("修改商品状态失败");
        }catch (Exception e){
            throw new ProductException("setSaleStatus",e.getClass()+e.getMessage());
        }
    }

    //3.获取商品详情的业务逻辑
    @Override
    public ServerResponse getProductDetail(Integer productId) {
        try{
            Product product = productMapper.selectByPrimaryKey(productId);
            if(product == null){
                return ServerResponse.createByErrorMessage("商品不存在");
            }
            ProductDetailVo productDetailVo = assembleProductDetailVo(product);
            return ServerResponse.createBySuccess(productDetailVo);
        }catch (Exception e){
            throw new ProductException("getProductDetail",e.getClass()+e.getMessage());
        }
    }

    //4.分页查找所有商品的业务逻辑
    @Override
    public ServerResponse getProductList(int pageNum, int pageSize,Integer ownerId) {
        try{
            PageHelper.startPage(pageNum,pageSize);//1.startPage
            List<Product> productList = productMapper.selectList(ownerId);
            List<ProductListVo> productListVoList = Lists.newArrayList();
            for(Product productItem : productList){
                User owner =  userMapper.selectByPrimaryKey(productItem.getOwnerId());
                ProductListVo productListVo = new ProductListVo();
                productListVo = productListVo.assembleProductListVo(productItem, owner.getUsername());
                productListVoList.add(productListVo);
            }
            PageInfo pageResult = new PageInfo(productList);
            pageResult.setList(productListVoList);
            return ServerResponse.createBySuccess(pageResult);
        }catch (Exception e){
            throw new ProductException("getProductList",e.getClass()+e.getMessage());
        }
    }

    //5.根据商名称或者商品Id组合分页查询
    @Override
    public ServerResponse searchProduct(Integer ownerId,String productName, Integer productId,  Integer enableStatus,int pageNum, int pageSize) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            if (StringUtils.isNotBlank(productName)) {
                productName = new StringBuilder().append("%").append(productName).append("%").toString();
            }
            List<Product> productList = productMapper.searchProducts(ownerId, productName, productId, enableStatus);
            List<ProductListVo> productListVoList = Lists.newArrayList();
            for (Product productItem : productList) {
                User owner = userMapper.selectByPrimaryKey(productItem.getOwnerId());
                ProductListVo productListVo = new ProductListVo();
                productListVo = productListVo.assembleProductListVo(productItem, owner.getUsername());
                productListVoList.add(productListVo);
            }
            PageInfo pageResult = new PageInfo(productList);
            pageResult.setList(productListVoList);
            return ServerResponse.createBySuccess(pageResult);
        }catch (Exception e){
            throw new ProductException("searchProduct",e.getClass()+e.getMessage());
        }
    }

    /**
     * 前端的业务逻辑
     *
     */
    //1.根据商品ID获取商品详情的业务逻辑，和后台不同的是这里的商品的状态是在线的
    @Override
    public ServerResponse<ProductDetailVo> portalGetProductDetail(Integer productId) {
        try {
            Product product = productMapper.selectByPrimaryKey(productId);
            if (product == null) {
                return ServerResponse.createByErrorMessage("产品不存在");
            }
            //判断商品的状态是否在线
            if (product.getEnableStatus() != ProductStatusEnum.ON_SALE.getStatus()) {
                return ServerResponse.createByErrorMessage("该商品尚未上架");
            }
            ProductDetailVo productDetailVo = assembleProductDetailVo(product);
            return ServerResponse.createBySuccess(productDetailVo);
        }catch (Exception e){
            throw new ProductException("portalGetProductDetail",e.getClass()+e.getMessage());
        }
    }

    //2.根据商品名，商品Id分页排序组合查询的业务逻辑
    @Override
    public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword, Integer categoryId,Integer ownerId,  int pageNum, int pageSize, String orderBy) {
        try {
            List<Integer> categoryIdList = Lists.newArrayList();
            if (categoryId != null) {
                Category category = categoryMapper.selectByPrimaryKey(categoryId);
                if (category == null && StringUtils.isBlank(keyword)) {
                    //没有该分类,并且还没有关键字,这个时候返回一个空的结果集,不报错
                    PageHelper.startPage(pageNum, pageSize);
                    List<ProductListVo> productListVoList = Lists.newArrayList();
                    PageInfo pageInfo = new PageInfo(productListVoList);
                    return ServerResponse.createBySuccess(pageInfo);
                }else{
                    categoryIdList = iCategoryService.selectCategoryAndChildrenById(category.getId()).getData();
                }
            }
            if (StringUtils.isNotBlank(keyword)) {
                keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
            }
            PageHelper.startPage(pageNum, pageSize);
            //排序处理
            if (StringUtils.isNotBlank(orderBy)) {
                String promotion_price_asc = ProductStatusEnum.PROMOTION_PRICE_ASC.getPromotion_price_oderBy();
                String promotion_price_desc = ProductStatusEnum.PROMOTION_PRICE_DESC.getPromotion_price_oderBy();
                if (promotion_price_asc.equals(orderBy)) {
                    String[] orderByArray = orderBy.split("_");
                    PageHelper.orderBy(orderByArray[0] + "_" + orderByArray[1] + " " + orderByArray[2]);
                } else if (promotion_price_desc.equals(orderBy)) {
                    String[] orderByArray = orderBy.split("_");
                    PageHelper.orderBy(orderByArray[0] + "_" + orderByArray[1] + " " + orderByArray[2]);
                } else {
                    return ServerResponse.createByIllegalArgument("前端输入的 价格排序 请求参数有误！！！");
                }
            }
            List<Product> productList = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword) ? null : keyword, categoryIdList.size() == 0 ? null : categoryIdList,ownerId);
            List<ProductListVo> productListVoList = Lists.newArrayList();
            for (Product productItem : productList) {
                User owner =  userMapper.selectByPrimaryKey(productItem.getOwnerId());
                ProductListVo productListVo = new ProductListVo();
                productListVo = productListVo.assembleProductListVo(productItem,owner.getUsername());
                productListVoList.add(productListVo);
            }
            PageInfo pageInfo = new PageInfo(productList);
            pageInfo.setList(productListVoList);
            return ServerResponse.createBySuccess(pageInfo);
        }catch (Exception e){
            throw new ProductException("getProductByKeywordCategory",e.getClass()+e.getMessage());
        }

    }

    @Override
    public ServerResponse getSellerProData(Integer ownerId) {
        try{
            Map<String,Integer> resultMap = Maps.newHashMap();
            int count = productMapper.selectCountByStatus(-1,ownerId);
            resultMap.put("status--1",count);
            count = productMapper.selectCountByStatus(0,ownerId);
            resultMap.put("status-0",count);
            count = productMapper.selectCountByStatus(1,ownerId);
            resultMap.put("status-1",count);
            count = productMapper.selectCountByStatus(2,ownerId);
            resultMap.put("status-2",count);
            return ServerResponse.createBySuccess(resultMap);
        }catch (Exception e){
            throw new ProductException("getSellerProData",e.getClass()+e.getMessage());
        }
    }

    private ProductDetailVo assembleProductDetailVo(Product product) {
        try {
            Integer categoryId = null;
            User owner = userMapper.selectByPrimaryKey(product.getOwnerId());
            Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
            if (category == null) {
                categoryId = 0;//默认跟几点
            } else {
                categoryId = category.getParentId();
            }
            ProductDetailVo productDetailVo = new ProductDetailVo();
            productDetailVo = productDetailVo.assembleProductDetailVo(product);
            productDetailVo.setParentCategoryId(categoryId);
            productDetailVo.setOwnerName(owner.getUsername());
            return productDetailVo;
        }catch (Exception e){
            throw new ProductException("searchProduct",e.getClass()+e.getMessage());
        }
    }

}
